package com.choosefine.it.worker.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.model.UserInfo;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.URLHandlerUtils;
import com.choosefine.it.team.model.TeamPublishFindWorkerInfo;
import com.choosefine.it.team.service.TeamPublishFindWorkerInfoService;
import com.choosefine.it.worker.model.FindWork;
import com.choosefine.it.worker.model.WorkerFavoriteWork;
import com.choosefine.it.worker.model.dto.WorkerInfoDTO;
import com.choosefine.it.worker.model.vo.WorkerFavoriteTeamVO;
import com.choosefine.it.worker.model.vo.WorkerFindWorkVO;
import com.choosefine.it.worker.model.vo.WorkerPublishVO;
import com.choosefine.it.worker.service.MyWorksManagerService;
import com.choosefine.it.worker.service.WorkerCenterService;
import com.github.pagehelper.Page;
import com.google.gson.Gson;

/**
 * 工人-->“我的” 选项卡 业务对外入口控制
 * 
 * @author liaozhanggen
 */
@Api(value = "工人-找工作|发布|个人中心功能", description = "廖仉根", protocols = "http", consumes = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/work")
public class WorkerCenterController extends BaseController {
	
	Gson gson = new Gson();
	Logger logger = LoggerFactory.getLogger(WorkerCenterController.class);
	@Autowired
	CustomRestTemplate restTemplate;

	public WorkerCenterController() {	}
	
	public WorkerCenterController(Object object) {
		if (object instanceof WorkerCenterService) {
			this.workerCenterService = (WorkerCenterService)object;
		}else if (object instanceof MyWorksManagerService){
			this.myWorksManagerService = (MyWorksManagerService)object;
		}else if (object instanceof TeamPublishFindWorkerInfoService) {
			this.teamPublishFindWorkerInfoService = (TeamPublishFindWorkerInfoService)object;
		}
	}

	@Autowired
	WorkerCenterService workerCenterService;

	@Autowired
	MyWorksManagerService myWorksManagerService;

	@Autowired
	TeamPublishFindWorkerInfoService teamPublishFindWorkerInfoService;
	
	@Value("#{yaml.get('basedata.projectType.getProjectTypeById')}")
	String projectTypeURL=null;
	
	@Value("#{yaml.get('basedata.userinfo.findUsersByRealName')}")
	String projectURL = null;
	
	@Value("#{yaml.get('basedata.companyInfo.getUserCodeByName')}")
	String companyURL=null;
	
	/**
	 * 对 工人已经收藏 各班组发布的招工人的信息 进行 ”失效“ 操作 - No. 10
	 * @throws BusinessException 
	 * 
	 * @auth liaozhanggen 2016-11-19 下午5:21:15
	 */
	@ResponseBody
	@ApiOperation("工人-我的-我的收藏列表-取消收藏功能")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "工人的userCode", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "uuid", value = "工人的uuid", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "publishId", value = "发布的ID", required = true, dataType = "Integer", paramType = "path")
	})
	@RequestMapping(method = RequestMethod.PUT, value = "/myfavorite/team_recruitment/cancel/{userCode}/{uuid}/{publishId}")
	public String myFavoriteTeamRecruitmentWorkCancel(
			@PathVariable String userCode,@PathVariable String uuid,@PathVariable Integer publishId) throws BusinessException {
		String result = null;
		Map<String, Object> params = new HashMap<>();
		params.put("userCode", userCode);
		params.put("uuid",uuid);
		params.put("publishId", publishId);
		params.put("type",CommonConstant.WORKER_COLLECT_TEAM);/*1：工人收藏班组发布找工人*/
		params.put("utime",System.currentTimeMillis());
		int num = myWorksManagerService.modifyFavoriteWorkStatus(params);
		result = num > 0 ? responseSuccess() : responseFail();
		return result;
	}

	/**
	 * 工人已经收藏 各班组发布的招工人的信息 列表 - No. 9
	 * 
	 * @auth liaozhanggen 2016-11-19 下午5:21:15
	 */
	@ApiOperation(value = "工人-我的-我的收藏列表功能",response = WorkerFavoriteWork.class)
	@ApiImplicitParams({
			@ApiImplicitParam(value = "工人的userCode",name = "userCode",required = true,dataType = "String",paramType = "path"),
			@ApiImplicitParam(value = "工人的uuid",name = "uuid",required = true,dataType = "String",paramType = "path"),
			@ApiImplicitParam(value = "起始页",name = "pageNum",required = true,dataType = "int",paramType = "query"),
			@ApiImplicitParam(value = "每页数",name = "pageSize",required = true,dataType = "int",paramType = "query")
	})
	@RequestMapping(method = RequestMethod.GET, value = "/myfavorite/team_recruitment/list/{userCode}/{uuid}")
	public String myFavoriteTeamRecruitmentWorkList(
			@PathVariable String userCode,
			@PathVariable String uuid,
			@RequestParam Integer pageNum,
			@RequestParam Integer pageSize)throws BusinessException {
		    Map map=new HashMap();
		    map.put("userCode",userCode);
			map.put("uuid",uuid);
			map.put("type",CommonConstant.WORKER_COLLECT_TEAM);/*1：工人收藏班组发布找工人*/
			PageDTO pageDTO=new PageDTO();
			pageDTO.setPageNum(pageNum);
			pageDTO.setPageSize(pageSize);
		    Page<WorkerFavoriteWork> favoriteWorks= myWorksManagerService.queryMyFavoriteTeamRecruitmentWorkPageByUuid(map,pageDTO);
			String result = responseSuccess(favoriteWorks);
			return result;
	}


	/**
	 * 查询 单条 各班组发布的招工人的信息 - No. 8
	 * @throws BusinessException 
	 * 
	 * @auth liaozhanggen 2016-11-19 下午3:31:07
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@ApiOperation(value="工人-开始找工作-找工作列表-具体招工信息",response=TeamPublishFindWorkerInfo.class)
	@RequestMapping(method = RequestMethod.GET, value = "/view/team/recruitment")
	public String viewTeamRecruitmentWorkInfo(@RequestParam(value = "trId", required = true) Integer trId,
												@RequestParam(value = "userCode", required = true) String userCode,
											  @RequestParam(value = "uuid",required = false)String uuid) throws BusinessException {
		Map map=new HashMap();
		map.put("publishId",trId);
		map.put("userCode",userCode);
		map.put("uuid",uuid);
		map.put("type",CommonConstant.WORKER_COLLECT_TEAM);//1：工人收藏班组发布找工人
		TeamPublishFindWorkerInfo trInfo = myWorksManagerService.findTeamRecruitmentInfoById(map);
		return responseSuccess(trInfo);
	}

	/**
	 * 得到ProjectUserCode值
	 * 
	 * @author liaozhanggen 2017年1月19日
	 */
	private String getAffCompanyUserCodeByName(String Affcompany) {
		if(!StringUtils.isEmpty(Affcompany)){
			StringBuffer urla=URLHandlerUtils.getUrlBuffer(shixiaobaoURL,  companyURL).append("/").append(Affcompany);
			Map mapsa= restTemplate.getForObject(urla.toString(), Map.class);
			return (String) mapsa.get("data");
		}
		return null;
	}

	/**
	 * 得到 ConstructionUnitUserCode值
	 * 
	 * @author liaozhanggen 2017年1月19日
	 */
	private String getConstructionUnitUserCodeByName(String constructionunit) {
		if(!StringUtils.isEmpty(constructionunit)){
			StringBuffer urlc=URLHandlerUtils.getUrlBuffer(shixiaobaoURL, companyURL).append("/").append(constructionunit);
			Map mapsc= restTemplate.getForObject(urlc.toString(), Map.class);
			return (String) mapsc.get("data");
		}
		return null;
	}

	/**
	 * 得到 AffCompanyUserCode值
	 * 
	 * @author liaozhanggen 2017年1月19日
	 */
	private String getProjectUserCodeByName(String projectcontractor) {
		if(!StringUtils.isEmpty(projectcontractor)){
			StringBuffer purl=URLHandlerUtils.getUrlBuffer(shixiaobaoURL,  projectURL).append(projectcontractor);
			Map map= restTemplate.getForObject(purl.toString(), Map.class);
			if(null != map.get("data")){
				Map arrays = (Map) map.get("data");
				return null == arrays ? null : (String) arrays.get("userCode");
			}
		}
		return null;
	}

	/**
	 * 添加工人收藏 各班组发布的招工人的信息 - No. 7
	 * @throws BusinessException 
	 * 
	 * @auth liaozhanggen 2016-11-19 下午3:31:07
	 */
	@ApiOperation("工人-开始找工作-找工作列表-具体招工信息-收藏(班组招工信息)功能")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "工人的userCode", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "uuid", value = "工人的uuid", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "publishId", value = "发布的ID", required = true, dataType = "Integer", paramType = "path")
	})
	@RequestMapping(method = RequestMethod.POST, value = "/favorite/team/recruitment/{userCode}/{uuid}/{publishId}")
	public String favoriteTeamRecruitmentWork(
			@PathVariable String userCode,@PathVariable String uuid,@PathVariable Integer publishId) throws BusinessException {
		String result = null;
		Map<String, Object> params = new HashMap<>();
		params.put("userCode", userCode);
		params.put("uuid",uuid);
		params.put("publishId", publishId);
		params.put("type",CommonConstant.WORKER_COLLECT_TEAM);/*1：工人收藏班组发布找工人*/
		params.put("ctime",System.currentTimeMillis());
		int num = myWorksManagerService.insertFavoriteWork(params);
		result = num > 0 ? responseSuccess(num) : responseFail(CommonConstant.COLLECT_DATA_EXISTS);
		return result;
	}

	/**
	 * 根据 地区、工种、及发布的时间 、推荐、工价 查询各班组发布的招工人数据集 - No. 6
	 * 
	 * @auth liaozhanggen 2016-11-19 上午11:19:09 update-yuxin-3.3
	 */
	@ResponseBody
	@ApiOperation(value = "工人-开始找工作-找工作列表(带条件过虑)和搜索",response = WorkerFindWorkVO.class)
	@RequestMapping(method = RequestMethod.GET, value = "/query/team/recruitment/{pageNum}/{pageSize}", produces = MediaType.APPLICATION_JSON_VALUE)
	@ApiImplicitParam(value = "工种/班组承包人姓名/项目名称/建筑公司名称",name = "random",required = false,dataType = "String",paramType = "query")
	public String queryTeamRecruitmentWork(@PathVariable("pageNum") Integer pageNum,
			@PathVariable(value="pageSize",required=true) Integer pageSize,
			@RequestParam(value = "area_code", required = false) String areaCode,
			@RequestParam(value = "work_type", required = false) String workType,
			@RequestParam(value = "orderBy", required = false) String orderBy,
			@RequestParam(value = "random",required = false) String random	 )
			throws Exception {
		/*
		 * 修改返回值为String 并修改封装PageDTO返回功能start guwenwei 2016/11/28
		 */
		Page<TeamPublishFindWorkerInfo> pageresult = null;
		Map<String, Object> params = new HashMap<String, Object>();
		// 根据地区
		params.put("areaCode", StringUtils.isEmpty(areaCode) ? null : areaCode.trim());
		// 根据工种
		params.put("worktype",StringUtils.isEmpty(workType) ? null : workType.trim());
		params.put("orderBy",StringUtils.isEmpty(orderBy) ? null : orderBy.trim());
		params.put("random",StringUtils.isEmpty(random)?null:random.trim());
		//分页处理
		pageresult = teamPublishFindWorkerInfoService.queryTeamRecruitmentPageByCondition(params, pageNum,pageSize);
		Page<WorkerFindWorkVO> lvot = entityTransfer(pageresult);	//实体之间的转换
		
		if (lvot.size() > 0) {
			lvot.setPages(pageresult.getPages());
			return responseSuccess(lvot);
		} else {
			return responseFail(ResultCode.MSG_DATA_ISEMPTY);
		}
		/*
		 * 修改返回值为String 并修改封装PageDTO返回功能end guwenwei 2016/11/28
		 */
	}
	/**
	 * 实体之间的转换
	 * 
	 * @author liaozhanggen 2017年1月18日
	 */
	private Page<WorkerFindWorkVO> entityTransfer(Page<TeamPublishFindWorkerInfo> pageresult) {
		Page<WorkerFindWorkVO> lvot = new Page<>();
		WorkerFindWorkVO vot= null;
		for(TeamPublishFindWorkerInfo temp : pageresult){
			vot = gson.fromJson(gson.toJson(temp), WorkerFindWorkVO.class);
            vot.setTeamUserCode(temp.getUserCode());
            vot.setConstructionunit(temp.getConstructionUnit());//yuxin
            vot.setCompanyUserCode(temp.getConstructionUnitCode());//yuxin
			
			//取usercode值
			String projectUserCode = getProjectUserCodeByName(temp.getProjectContractor());
			if(!StringUtils.isEmpty(projectUserCode)){
				 vot.setProjectUserCode(projectUserCode);
			}
			String companyUserCode = getConstructionUnitUserCodeByName(temp.getConstructionUnit());
			if (!StringUtils.isEmpty(companyUserCode)) {
				vot.setCompanyUserCode(companyUserCode);
			}
			String affCompanyUserCode = getAffCompanyUserCodeByName(temp.getAffcompanyName());
			if(!StringUtils.isEmpty(affCompanyUserCode)){
				vot.setAffCompanyUserCode(affCompanyUserCode);
			}
            
            lvot.add(vot);
		}
		
		return lvot;
	}

	/**
	 * 工作人-查看收到评价的工作 列表 - No. 5
	 * 
	 * @auth liaozhanggen 2016-11-18 下午5:50:57
	 * @param userCode
	 * @throws BusinessException 
	 */
//	@ResponseBody
//	@ApiOperation("工人-我的-收到的评价列表功能")
//	@RequestMapping(method = RequestMethod.POST, value = "/query/receive/{userCode}/comment", produces = MediaType.APPLICATION_JSON_VALUE)
//	public String receiveCommentWork(@RequestBody PageDTO pageDTO,@PathVariable("userCode") String userCode) throws BusinessException {
//
//		String result = null;
//		UserInfo userDto = new UserInfo(userCode);
//		
//		Page<WorksAppraise> worksAppraises= myWorksManagerService.queryWorkComment(userDto, pageDTO);
//		Page<WorkCommentVO> wList = commentTransferVO(worksAppraises); //评论实体返回结果替换
//	    
//	    if(wList.size()>0){
//	    	wList.setPages(worksAppraises.getPages());
//	    	result = responseSuccess(wList);
//	    }else{
//	    	result = responseFail(ResultCode.MSG_DATA_ISEMPTY);
//	    }
//		userDto = null;
//		return result;
//	}

	/**
	 * 评论实体返回结果替换
	 * 
	 * @author liaozhanggen 2017年1月18日
	 */
//	private Page<WorkCommentVO> commentTransferVO(Page<WorksAppraise> worksAppraises) {
//		WorkCommentVO vo= null;
//		Page<WorkCommentVO> wList= new Page<WorkCommentVO>();
//		for (WorksAppraise temp : worksAppraises) {
//			vo = new WorkCommentVO();
//			ProjectInfo projectInfo = temp.getProjectInfo();
//			if(projectInfo!=null){
//			vo.setProjectEnd(projectInfo.getProjectEnd());
//			vo.setProjectName(projectInfo.getProjectName());
//			vo.setProjectStart(projectInfo.getProjectStart());}
//			
//			ItemInfo itemInfo = temp.getItemInfo();
//			if(itemInfo!=null){
//			vo.setUserName(itemInfo.getUserName());
//			vo.setTeamName(itemInfo.getTeamName());
//			}
//			vo.setCityName(temp.getCityName());
//			vo.setCtime(temp.getCtime());
//			vo.setSkillLevel(temp.getSkillLevel());
//			vo.setWorkLevel(temp.getWorkLevel());
//			vo.setWorkTypeName(temp.getWorkTypeName());
//			
//			wList.add(vo);
//		}
//		return wList;
//	}

	/**
	 * 添加对工人的工作评价的记录 - No. 4
	 * 
	 * @param
	 * @throws BusinessException 
	 */
//	@ResponseBody
//	@ApiOperation("控制台-添加对工人的工作评价功能")
//	@RequestMapping(method = RequestMethod.POST, value = "/add/comment", produces = MediaType.APPLICATION_JSON_VALUE)
//	public String addWorkerCommentWork(@RequestBody WorkerCommentDTO workerCollectionDTO) throws BusinessException {
//		int num = myWorksManagerService.addWorkComment(workerCollectionDTO);
//		return num > 0 ? this.responseSuccess() : responseFail();
//	}

	/**
	 * 根据当前登录人，查看用户的“个人详情”信息 - No. 11
	 * 
	 * @param userCode
	 * 
	 */
	@ResponseBody
	@ApiOperation(value = "工人-我的-个人主页基本信息功能",response = UserInfo.class)
	@RequestMapping(method = RequestMethod.GET, value = "/query/{userCode}/uinfo")
	public String queryUserInfo(@PathVariable("userCode") String userCode) throws BusinessException {
		String result = null;
//		WorkhomepageVO wvo = null;
		UserInfo userInfo = workerCenterService.findUserSingleDetailById(userCode);
		result=responseSuccess(userInfo);
		return result;
	} 
	

	/**
	 * 根据当前登录人，更新用户的“个人详情”信息 - No. 12
	 * 
	 * @param
	 * @throws BusinessException 
	 */
	@ResponseBody
	@ApiOperation("工人-我的-更新用户的“个人主页”信息功能")
	@RequestMapping(method = RequestMethod.POST, value = "/modify/uinfo", produces = MediaType.APPLICATION_JSON_VALUE)
	public String modifyUserInfo(@RequestBody WorkerInfoDTO w) throws BusinessException {

		String result = null;
		UserInfo userInfo=new UserInfo();
		/*userInfo.setSkillsCcie(w.getSkillsCcie());*/
		userInfo.setRegistAddress(w.getRegistAddress());
		userInfo.setContactAddress(w.getContactAddress());
		userInfo.setPhoneNumber(w.getPhoneNumber());
		userInfo.setUserCode(w.getUserCode());
		
		int num = workerCenterService.updateUserInfo(userInfo);
		result = num > 0 ? responseSuccess() : responseFail();
		return result;
	}

	/**
	 * 工作人-发布工作管理列表查询 - No. 2
	 * 
	 * @param userCode
	 * @throws BusinessException 
	 */
	@ResponseBody
	@ApiOperation("工人-我的-发布工作管理列表查询功能")
	@RequestMapping(method = RequestMethod.GET, value = "/query/{userCode}/mypublish/{pageNum}/{pageSize}/{orderBy}/{verifyStatus}")
	public String queryMyPublishWorkMsg(
			@PathVariable("userCode") String userCode,
			@PathVariable("pageNum") Integer pageNum,
			@PathVariable("pageSize") Integer pageSize,
			@PathVariable("orderBy") String orderBy,
			@PathVariable("verifyStatus") Integer verifyStatus) throws BusinessException {
		String result = null;
		PageDTO pageDto = new PageDTO();
		pageDto.setPageNum(pageNum);
		pageDto.setPageSize(pageSize);
		pageDto.setOrderBy(orderBy);
		
		Map<String, Object> param = new HashMap<>();
		param.put(CommonConstant.USER_CODE, userCode);
		param.put("verifyStatus",verifyStatus);
		Page<FindWork> jsonResult = workerCenterService.queryPublishWorkMgt(param, pageDto);
		WorkerPublishVO wcvf= null;
		Page<WorkerPublishVO> lwvcf=new Page<WorkerPublishVO>();
		for (FindWork fWork : jsonResult) {
			wcvf = gson.fromJson(gson.toJson(fWork), WorkerPublishVO.class);
			lwvcf.add(wcvf);
			wcvf = null;
		}
		lwvcf.setPages(jsonResult.getPages());
		result = responseSuccess(lwvcf);
		pageDto = null;
		return result;
	}

	/**
	 * 工作人-发布工作- No. 1
	 * 
	 * @param
	 * @throws BusinessException 
	 */
	@ResponseBody
	@ApiOperation("工人-发布工作")
	@RequestMapping(method = RequestMethod.POST, value = "/publish", produces = MediaType.APPLICATION_JSON_VALUE)
	public String publishWork(@RequestBody FindWork findWork) throws BusinessException {
		String result = null;
		int num = workerCenterService.insertPublishWork(findWork);
		result = num > 0 ? responseSuccess() : responseFail();
		return result;
	}
}
